#!/usr/bin/env python
# encoding: utf-8

from app.views.api import route_api
from  flask import request,jsonify,g
import requests,json,decimal

from app import db
from app.model import User
from app.model import Electronic
from app.model import ElectronicOrder
from app.model import ElectronicOrderLog
from app.model import ElectronicOrderItem

from app.common.libs.Helper import getFormatDate, getCurrentDate
from app.common.libs.electronic.OrderService import OrderService
from app.common.libs.UserService import UserService
from sqlalchemy import func, desc

@route_api.route("/electronicOrder/create",methods = [ "GET","POST" ])
def electronicOrderCreate():
    resp = { 'code':20000,'message':'创建成功~', 'data':{}}

    if request.method == 'POST':
        data = request.get_data()
        json_data = json.loads(data.decode('utf-8'))
        try:
            # 创建订单
            order_model = ElectronicOrder()
            order_model.type = json_data['type']
            order_model.count = json_data['count']
            order_model.note = json_data['note']
            order_model.sn = OrderService.geneSn()
            order_model.status = 1
            order_model.created_time = order_model.updated_time = getCurrentDate()
            user_info = UserService.getUserInfo(request)
            order_model.user_id = user_info.id
            db.session.add( order_model )
            db.session.commit()
            # 创建订单所需元器件
            ids = json_data['electronic_ids']
            cnts = json_data['electronic_cnts']
            for id_, cnt in zip(ids, cnts):
                order_item_model = ElectronicOrderItem()
                order_item_model.electronic_order_id = order_model.id
                order_item_model.electronic_id = id_
                order_item_model.count = cnt
                db.session.add( order_item_model )
            # 添加操作日志
            order_log_model = ElectronicOrderLog()
            order_log_model.electronic_order_id = order_model.id
            order_log_model.created_time = getCurrentDate()
            order_log_model.status = 1
            order_log_model.log = '创建订单'
            order_log_model.user_id = user_info.id
            db.session.add(order_log_model)
            db.session.commit()

        except Exception as e:
            print(e)
            db.session.rollback()
            resp['code'] = -1
            resp['message'] = "下单失败请重新下单"
            return jsonify( resp )

    return jsonify( resp )

@route_api.route("/electronicOrder/fetch",methods = [ "GET","POST" ])
def electronicOrderFetch():
    resp = { 'code':20000,'message':'创建成功~', 'data':{}}
    req = request.values
    page = int( req['page'] ) if 'page' in req else 0
    limit = int( req['limit'] ) if 'limit' in req else 0
    offset = ( page - 1 ) * limit

    user_info = UserService.getUserInfo(request)
    if user_info.roles == 'admin':
        query = db.session.query( ElectronicOrder, User ).filter(ElectronicOrder.user_id == User.id)
    if user_info.roles == '库管':
        query = db.session.query( ElectronicOrder, User ).filter(ElectronicOrder.user_id == User.id)
    if user_info.roles == '采购':
        query = db.session.query( ElectronicOrder, User ).filter(ElectronicOrder.user_id == User.id)
    if user_info.roles == '研发':
        query = db.session.query( ElectronicOrder, User )\
            .filter(ElectronicOrder.user_id == User.id)\
            .filter(User.id == user_info.id)
    if 'sn' in req:
        sn = req['sn']
        if sn:
            query = query.filter(ElectronicOrder.sn.like('%'+sn+'%'))
    if 'status' in req:
        if req['status']:
            status = int( req['status'] )
            query = query.filter(ElectronicOrder.status == status)
    if 'type' in req:
        if req['type']:
            type = int( req['type'] )
            query = query.filter(ElectronicOrder.type == type)
    total = query.count()
    order_list = query.order_by(desc(ElectronicOrder.created_time)).offset( offset ).limit( limit ).all()
    items = [{
            'id':item.id,
            'sn':item.sn,
            'status':item.status,
            'type':item.type,
            'created_time':getFormatDate(item.created_time),
            'user': user.nickname
        } for item, user in order_list]

    resp['data']['items'] = items
    resp['data']['total'] = total

    return jsonify( resp )

@route_api.route("/electronicOrder/delete/<int:id>",methods = [ "GET","POST" ])
def electronicOrderDelete(id):
    resp = { 'code':20000,'message':'删除成功~', 'data':{}}
    order = ElectronicOrder.query.filter_by(id = id).first()
    if not order:
        resp['code'] = -1
        resp['message'] = '订单不存在'
        return jsonify( resp )
    db.session.delete(order)
    # 删除订单下的item
    order_items = ElectronicOrderItem.query.filter_by(electronic_order_id = id).all()
    for item in order_items:
        db.session.delete(item)
    # 删除订单下的操作日志
    order_log = ElectronicOrderLog.query.filter_by(electronic_order_id = id).all()
    for log in order_log:
        db.session.delete(log)
    db.session.commit()
    return jsonify( resp )

@route_api.route("/electronicOrder/detail/<int:id>",methods = [ "GET","POST" ])
def electronicOrderDetail(id):
    resp = { 'code':20000,'message':'创建成功~', 'data':{}}
    electronic_order_items = db.session.query( Electronic, ElectronicOrderItem)\
        .filter(ElectronicOrderItem.electronic_id == Electronic.id)\
        .filter(ElectronicOrderItem.electronic_order_id == id)\
        .all()
    electronicList = []
    totalAmount = 0
    for electronic, item in electronic_order_items:
        amount = int(item.count) * float(electronic.price)
        totalAmount += amount
        electronicList.append({
            'order_id': item.id,
            'order_count': item.count,
            'electronic_id': electronic.id,
            'electronic_sn': electronic.sn,
            'electronic_name': electronic.name,
            'electronic_position': electronic.position,
            'electronic_package': electronic.package,
            'electronic_spec': electronic.spec,
            'electronic_price': str(electronic.price),
            'electronic_stock': electronic.stock,
            'electronic_supplier': electronic.supplier,
        })
    # 获取订单详情
    user_info = UserService.getUserInfo(request)
    info = db.session.query( ElectronicOrder, User )\
                .filter(ElectronicOrder.user_id == User.id)\
                .filter(ElectronicOrder.id == id)\
                .first()
    order_info = info[0]
    user_info = info[1]
    order = {
        'id':order_info.id,
        'sn':order_info.sn,
        'status':order_info.status,
        'type':order_info.type,
        'note':order_info.note,
        'created_time':getFormatDate(order_info.created_time),
        'totalAmount':totalAmount
    }
    user = {
        'id':user_info.id,
        'nickname':user_info.nickname,
        'mobile':user_info.mobile
    }
    # 获取订单操作记录
    log_info = db.session.query( ElectronicOrderLog, User)\
                .filter(ElectronicOrderLog.electronic_order_id == id)\
                .filter(ElectronicOrderLog.user_id == User.id)\
                .all()
    logList = [{
        'user': user.nickname,
        'log': log.log,
        'status': log.status,
        'created_time': getFormatDate(log.created_time)
    } for log, user in log_info]

    resp['data']['user'] = user
    resp['data']['order'] = order
    resp['data']['electronicList'] = electronicList
    resp['data']['logList'] = logList

    return jsonify( resp )

@route_api.route("/electronicOrder/outstock",methods = [ "GET","POST" ])
def electronicOrderOutstock():
    resp = { 'code':20000,'message':'出库完成~', 'data':{}}
    req = request.values
    id = int(req['id']) if 'id' in req else 0

    order = ElectronicOrder.query.filter_by(id = id).first()
    if not order:
        resp['code'] = -1
        resp['message'] = '订单不存在'
        return jsonify( resp )
    # 出库元器件
    order_items = db.session.query(ElectronicOrderItem, Electronic)\
        .filter(ElectronicOrderItem.electronic_order_id == id)\
        .filter(ElectronicOrderItem.electronic_id == Electronic.id)\
        .all()
    items = [{
        'electronic_name':electronic.name,
        'electronic_id':item.electronic_id,
        'count':item.count
    } for item, electronic in order_items]
    resp = OrderService.outStock(items=items)
    # 修改订单状态
    order.status = 2
    # 添加操作记录
    content = req['content'] if 'content' in req else ''
    order_log = ElectronicOrderLog()
    order_log.status = 2
    order_log.log = content
    order_log.created_time = getCurrentDate()
    order_log.electronic_order_id = order.id
    user_info = UserService.getUserInfo(request)
    order_log.user_id = user_info.id

    db.session.add(order_log)
    db.session.commit()
    return jsonify( resp )

# 订单状态变化记录
@route_api.route("/electronicOrder/changeStatus",methods = [ "GET","POST" ])
def electronicOrderChangeStatus():
    resp = { 'code':20000,'message':'操作成功~', 'data':{}}
    req = request.values
    user_info = UserService.getUserInfo(request)
    id = int(req['id']) if 'id' in req else 0
    status = int(req['status']) if 'status' in req else 0
    content = req['content'] if 'content' in req else ''
    order = ElectronicOrder.query.filter_by(id = id).first()
    if not order:
        resp['code'] = -1
        resp['message'] = '订单不存在'
        return jsonify( resp )
    if status == 2: # 出库订单
        # 出库元器件
        receiver_id = int(req['receiver_id']) if 'receiver_id' in req else 0
        order_items = db.session.query(ElectronicOrderItem, Electronic)\
            .filter(ElectronicOrderItem.electronic_order_id == id)\
            .filter(ElectronicOrderItem.electronic_id == Electronic.id)\
            .all()
        items = [{
            'electronic_name':electronic.name,
            'electronic_id':item.electronic_id,
            'receiver_id':receiver_id,
            'operater_id':user_info.id,
            'count':item.count
        } for item, electronic in order_items]
        resp = OrderService.outStock(items=items)

    # 修改订单状态
    order.status = status
    # 添加操作记录
    order_log = ElectronicOrderLog()
    order_log.status = status
    order_log.log = content
    order_log.created_time = getCurrentDate()
    order_log.electronic_order_id = order.id
    order_log.user_id = user_info.id
    db.session.add(order_log)
    db.session.commit()


    return jsonify( resp )

